package com.yangyouqi.chaper8.inti;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author 杨友奇
 * @Time 2018/7/26
 */
@Component
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class InitProject implements ApplicationRunner {
    private static final Logger LOG = LoggerFactory.getLogger(InitProject.class);

    @Autowired
    DataSource dataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        LOG.info("==========init project===========");
        LOG.info("=========get dataSource==========={}", dataSource);
        //读取sql脚本
        try {
            ClassPathResource recordsSys = new ClassPathResource("data.sql");
            DataSourceInitializer dsi = new DataSourceInitializer();
            dsi.setDataSource(dataSource);
            dsi.setDatabasePopulator(new ResourceDatabasePopulator(true, true, "utf-8", recordsSys));
            dsi.setEnabled(true);
            dsi.afterPropertiesSet();
            LOG.info("============init sql success============");
        } catch (Exception e) {
            LOG.error("init sql error={}", e.getMessage());
        }

    }
}

